<?php
namespace app\common\service;


use think\Db;
use think\Model;

class ClassesService extends BaseService
{
    /**
     * 添加班级
     * @param $sid
     * @param $postParam
     * @return array
     */
    public function AddClass($sid,$postParam){
        //是否重名
        $info = db('classes')->where(['sid' => $sid,'name' => $postParam['name'], 'status' => ['<>', -1]])->find();
        if(!empty($info)){
            return ['status' =>0,'msg' =>'班级名称重名，请重新填写！'];
        }

        //插入数据
        $add_data = [
            'name' => $postParam['name'],
            'description' => $postParam['description'] ?? '',
            'magazine_cate_id' => $postParam['magazine_cate_id'] ?? 0,
            'status' => 1,
            'addtime' => time(),
            'sid' => $sid,
            'course_push_tpl_id' => $postParam['course_push_tpl_id'] ?? 0
        ];
        if($this->isTemplateStore($sid)){
            if(!isset($postParam['academy_id'])){
                return ['status' =>0,'msg' =>'学院不能为空！'];
            }
            //模版店铺插入的数据
            $add_data['upper_limit'] = 200;  //人数上限默认设置为200
            $add_data['teaching_status'] = 1;
            $add_data['campus_id'] = 0;
            $add_data['academy_id'] = $postParam['academy_id'];
        } else {
            $add_data['upper_limit'] = $postParam['upper_limit'];
            $add_data['teaching_status'] = $postParam['status'];
            $add_data['campus_id'] = $postParam['campus_id'] ?? 0;
        }

        $origin_class_id = db('classes')->insertGetId($add_data);
        if($origin_class_id === false){
            return ['status' => 0,'msg' => '新增班级失败！'];
        }

        if($this->isTemplateStore($sid)){
            //推送模板消息
            $wx_tpl_service = new WxTplMsgService();
            $tpl_store_service = new TemplateStoreService();
            $sids = $tpl_store_service->getSameAcademyStoreIdList($postParam['academy_id']);
            if($sids){
                foreach($sids as $k => $v){
                    $wx_tpl_service->send($v, $origin_class_id, 'template_store_class');
                }
            }
            /*//获取同学院下的店铺
            $academy_id = db('store')->where(['store_id' => $sid])->value('academy_id');
            $store_list = db('store')->field('store_id')->where(['academy_id' => $academy_id, 'store_id' => ['<>' , $sid]])->select();
            $data = [];
            if($store_list){
                foreach($store_list as $k => $v){
                    $class_info = db('classes')->where(['sid' => $v['store_id'], 'status' => 1, 'name' => $postParam['name']])->find();
                    //不存在则插入
                    if(empty($class_info)){
                        $data[$k]['name'] = $postParam['name'];
                        $data[$k]['upper_limit'] = 200;
                        $data[$k]['description'] = $postParam['description'] ?? '';
                        $data[$k]['teaching_status'] = 1;
                        $data[$k]['status'] = 1;
                        $data[$k]['addtime'] = time();
                        $data[$k]['sid'] = $v['store_id'];
                        $data[$k]['campus_id'] = 0;
                        $data[$k]['origin_classid'] = $origin_class_id;
                    }
                }
                $res = db('classes')->insertAll($data);
                if(!$res){
                    return ['status' => 0, 'msg' => '新增失败'];
                }
            }*/
        }

        return ['status' => 1, 'msg' => '新增成功'];
    }


    /**
     * 编辑班级
     * @param $sid
     * @param $classid
     * @param $postParam
     * @return array
     * @throws \think\Exception
     */
    public function EditClass($sid,$classid,$postParam){
        $info = db('classes')->where(['sid' => $sid,'name' => $postParam['name'],'classid' =>['neq',$classid], 'status' => ['<>', -1]])->find();
        if(!empty($info)){
            return ['status' =>0,'msg' =>'班级名称重名，请重新填写！'];
        }

        //更新数据
        $update_data = [
            'name' => $postParam['name'],
            'description' => $postParam['description'] ?? '',
            'edittime' => time(),
            'course_push_tpl_id' => $postParam['course_push_tpl_id'] ?? 0
        ];
        if(!$this->isTemplateStore($sid)){
            //非模版店铺还需要更新的数据
            $update_data['upper_limit'] = $postParam['upper_limit'];
            $update_data['teaching_status'] = $postParam['status'];
            $update_data['campus_id'] = $postParam['campus_id'] ?? 0;
            $update_data['magazine_cate_id'] = $postParam['magazine_cate_id'] ?? 0;
        }

        $res = db('classes')->where(['classid' => $classid])->update($update_data);
        if($res === false){
            return ['status' => 0,'msg' => '编辑班级失败！'];
        }else{
            return ['status' => 1];
        }
    }

    /**
     * 获取班级详情
     * @param $sid
     * @param $classid
     * @return array
     */
    public function GetClassDetail($sid,$classid){
        $where = [
            'cl.sid' => $sid,
            'cl.classid' => $classid,
            'cl.status' => ['neq',-1]
        ];
        $info = db('classes cl')
                ->field('cl.*,ca.id as campus_id,cpt.tpl_name')
                ->join('campus ca','ca.id=cl.campus_id','LEFT')
                ->join('course_push_tpl cpt', 'cpt.id=cl.course_push_tpl_id', 'LEFT')
                ->where($where)
                ->find();
        if(empty($info)){
            return ['status' => 0,'msg' => '未找到该班级'];
        }else{
            //班级状态
            if($info['status'] == 0){
                $info['status_str'] = '已结业';
            }else{
                if($info['teaching_status'] ==0){
                    $info['status_str'] = '未开课';
                }else{
                    $info['status_str'] = '已开课';
                }
            }
            $info['addtime'] = date('Y-m-d',$info['addtime']);


            $info['total_numbe_db'] = $this->GetClassStudentsCount($sid,$classid);
            $info['total_numbe'] = $this->GetClassStudentsCount($sid,$classid);

            $data['content'] = $info;
            return ['status' => 1,'data' => $data];
        }
    }

    /**
     * 获取班级列表
     * @param $sid
     * @param int $type
     * @param string $search
     * @param int $p
     * @param int $pageSize
     * @return false|\PDOStatement|string|\think\Collection
     */
    public function GetClassList($sid, $type = 0, $search = '', $campus_id = 0, $p = 1, $pageSize = 10){
        $where = [
            'sid' => $sid
        ];
        $condition = [
            'cl.sid' => $sid
        ];
        if(!empty($search)){
            $where['name'] = ['like','%'.$search.'%'];
            $condition['cl.name'] = ['like','%'.$search.'%'];
        }
        if($campus_id != 0){
            $where['campus_id'] = $campus_id;
            $condition['cl.campus_id'] = $campus_id;
        }
        if($type == 0){
            //全部课程
            $where['status'] = ['neq',-1];
            $condition['cl.status'] = ['neq',-1];
        }
        if($type == 1){
            //未授课
            $where['teaching_status'] = 0;
            $where['status'] = 1;

            $condition['cl.teaching_status'] = 0;
            $condition['cl.status'] = 1;
        }
        if($type == 2){
            //已授课
            $where['teaching_status'] = 1;
            $where['status'] = 1;

            $condition['cl.teaching_status'] = 1;
            $condition['cl.status'] = 1;
        }
        if($type == 3){
            $where['status'] = 0;
            $condition['cl.status'] = 0;
        }
        $list_count = db('classes')->where($where)->count();
        $list = db('classes cl')
                ->field('cl.*,ca.id as campus_id,ca.name as campus_name,mc.title as magazine_cate_name')
                ->join('campus ca', 'ca.id=cl.campus_id', 'LEFT')
                ->join('magazine_category mc', 'mc.cate_id=cl.magazine_cate_id', 'LEFT')
                ->where($condition)
                ->order('cl.addtime DESC')
                ->limit(($p-1)*$pageSize,$pageSize)
                ->select();
        if(!empty($list)){
            foreach($list as $k => $v){
                $list[$k]['addtime'] = date('Y-m-d',$v['addtime']);
                $list[$k]['total_numbe'] = $this->GetClassStudentsCount($sid,$v['classid']);
                //班级状态
                if($v['status'] == 0){
                    $list[$k]['status_str'] = '已结业';
                }else{
                    if($v['teaching_status'] ==0){
                        $list[$k]['status_str'] = '未开课';
                    }else{
                        $list[$k]['status_str'] = '已开课';
                    }
                }
            }
        }
        return ['content' => $list,'page' =>['count' =>$list_count]];
    }

    /**
     * 班级结课
     * @param $sid
     * @param $classid
     * @return array
     * @throws \think\Exception
     */
    public function EditClassStatus($sid,$classid){
        $where = [
            'sid' => $sid,
            'classid' => $classid,
            'status' => ['neq',-1]
        ];
        $info = db('classes')->where($where)->find();
        if(empty($info)){
            return ['status' => 0,'msg' => '该班级不存在'];
        }
        if($info['status'] == 0){
            return ['status' => 0,'msg' => '该班级已经是结课状态'];
        }
        $res = db('classes')->where($where)->update(['status' => 0]);
        if($res === false){
            return ['status' => 0,'msg' => '操作失败！'];
        }else{
            return ['status' => 1];
        }
    }
    public function GetClassStudentsCount($sid,$classid)
    {
//        $count = db('class_students')->where(['sid'=>$sid,'classid'=>$classid])->count();
        $where = [
            's.sid' => $sid,
            'cs.classid' => $classid
        ];
        $count = db('students s')
                ->join('class_students cs','s.id = cs.studentsid')
                ->where($where)
                ->count();
        return $count;
    }
    /**
     * 删除班级
     * @param $sid
     * @param $classid
     * @return array
     * @throws \think\Exception
     */
    public function DelClass($sid,$classid){
        $where = [
            'sid' => $sid,
            'classid' => $classid,
            'status' => ['neq',-1]
        ];
        $info = db('classes')->where($where)->find();
        if(empty($info)){
            return ['status' => 0,'msg' => '该班级不存在'];
        }
        //是否有相关学员
        $student_list = db('class_students')->where(['sid' => $sid,'classid' => $classid])->find();
        if($student_list){
            return ['status' => 0,'msg' => '该班级下还有学员，请先解绑学员！'];
        }
        //是否有相关课程
        $course_list = db('course_class')->where(['classid' => $classid])->find();
        if($course_list){
            return ['status' => 0,'msg' => '该班级下还有课程，请先解绑课程！'];
        }
        $res = db('classes')->where($where)->update(['status' => -1]);
        if($res === false){
            return ['status' => 0,'msg' => '操作失败！'];
        }else{
            return ['status' => 1];
        }
    }

    /**
     * 班级添加学员
     * @param $sid
     * @param $classid
     * @param $postParam
     * @return array
     * @throws \think\Exception
     */
    public function AddStudents($sid,$classid,$postParam){
        // 这里应该是UID是0，也应该能写入
        // 真正关联的是手机号码
        //
        /*$uid = $postParam['uid'];
        if(empty($uid) || !is_array($uid)){
            return ['status' => 0,'msg' => '参数错误'];
        }*/

        $studentsids = $postParam['studentsid'];
        if(empty($studentsids) || !is_array($studentsids)){
            return ['status' => 0,'msg' => '参数错误'];
        }

        //班级信息
        $class_info = db('classes')->where(['classid' => $classid,'status' => ['neq',-1],'sid' => $sid])->find();
        if(empty($class_info)){
            return ['status' => 0,'msg' => '该班级不存在！'];
        }
        if($class_info['status'] == 0){
            return ['status' => 0,'msg' => '该班级已经结课!'];
        }
        if($class_info['total_numbe']+count($studentsids) > $class_info['upper_limit']){
            return ['status' => 0,'msg' => '此次添加人数超过该班级的人数上线!'];
        }
        // 查询出学员ID

//        foreach($uid as $v){
        foreach($studentsids as $v){
            /*$student_info_temp = db('students')->where(['uid' => $v, 'sid' => $sid])->find();
            $studentsid = $student_info_temp['id'];*/
            $uid = db('students')->where(['id' => $v, 'sid' => $sid])->value('uid');
            //存入关联表
            $data = [
//                'uid' => $v,
                'uid' => $uid ?? 0,
                'classid' => $classid,
//                'studentsid' => $studentsid,
                'studentsid' => $v,
                'sid' => $sid,
                'addtime' => time()
            ];
            $cs_info = db('class_students')->where(['uid' => $uid, 'classid' => $classid, 'studentsid' => $v, 'sid' => $sid])->find();
            if($cs_info){
                $re = true;
            } else {
                $re = db('class_students')->insert($data);
            }

            if(!$re){
                return ['status' => 0,'msg' => '保存失败'];
            }else{
                //将添加学员和课程关联起来
                //查找course_class
                $ccids = db('course_class')->where(['classid'=>$classid])->field('courseid')->select();
                if($ccids){
//                    $cs_data['uid'] = $v;
                    $cs_data['uid'] = $uid ?? 0;
                    $cs_data['sid'] = $sid;
                    $cs_data['attend_status'] = 0;
                    $cs_data['sign_status'] = 0;
                    $cs_data['addtime'] = time();
                    $cs_data['formal_status'] = 1;
                    $cs_data['ourclass_status'] = 1;
                    $cs_data['apply_status'] = 0;
                    foreach($ccids as $vo){
                        $cs_data['courseid']=$vo['courseid'];
                        //防止重复插入课程学员信息
                        $r = db('course_students')
                            ->where([
                                'sid' => $sid,
//                                'uid' => $v,
                                'courseid' => $vo['courseid'],
                                'sign_status' => 0,
                                'formal_status' => 1,
                                'ourclass_status' => 1,
                                'apply_status' => 0,
//                                'studentsid' => $studentsid
                                'studentsid' => $v
                            ])
                            ->find();
                        if(empty($r)){
                            db('course_students')->insert($cs_data);
                        }
                    }
                }
            }
        }
        db('classes')->where(['sid'=>$sid,'classid'=>$classid])->setInc('total_numbe',count($uid));
        return ['status' => 1];

    }

    /**
     * 班级添加课程
     * @param $sid
     * @param $classid
     * @param $postParam
     * @return array
     * @throws \think\Exception
     */
    public function AddCourse($sid,$classid,$postParam){
        $ids = $postParam['courseid'];
        if(empty($ids) || !is_array($ids)){
            return ['status' => 0,'msg' => '参数错误'];
        }
        //班级信息
        $class_info = db('classes')->where(['classid' => $classid,'status' => ['neq',-1],'sid' => $sid])->find();
        if(empty($class_info)){
            return ['status' => 0,'msg' => '该班级不存在！'];
        }
        if($class_info['status'] == 0){
            return ['status' => 0,'msg' => '该班级已经结课!'];
        }

        foreach($ids as $v){
            //存入关联表
            $data = [
                'courseid' => $v,
                'classid' => $classid,
                'addtime' => time()
            ];
            $re = db('course_class')->insert($data);
            if(!$re){
                return ['status' => 0,'msg' => '保存失败'];
            }else{
                //将班级中学员和课程关联起来
                //查找class_students
//                $uids = db('class_students')->where(['classid' => $classid])->field('uid')->select();
                /*$uids = db('class_students')->where(['classid' => $classid, 'uid' => ['>', 0]])->field('uid,studentsid')->select();
                if($uids){
                    foreach($uids as $key => $val){
                        $cs_data[$key]['courseid'] = $v;
                        $cs_data[$key]['sid'] = $sid;
                        $cs_data[$key]['attend_status'] = 0;
                        $cs_data[$key]['sign_status'] = 0;
                        $cs_data[$key]['addtime'] = time();
                        $cs_data[$key]['formal_status'] = 1;
                        $cs_data[$key]['ourclass_status'] = 1;
                        $cs_data[$key]['apply_status'] = 0;
                        $cs_data[$key]['uid'] = $val['uid'];
                        $cs_data[$key]['studentsid'] = $val['studentsid'];
                    }
                    db('course_students')->insertAll($cs_data);
                }*/
            }
        }
        return ['status' => 1];
    }

    /**
     * 获取班级相关课程
     * @param $sid
     * @param $classid
     * @param int $p
     * @param int $pageSize
     * @return mixed
     */
    public function GetOwnClassCourseList($sid,$classid,$p = 1,$pageSize = 10){
        $where = [
            'cc.classid' => $classid,
            'c.sid' => $sid
        ];
        $list_count = db('course_class')->alias('cc')
                    ->join('course c','c.courseid = cc.courseid')
                    ->where($where)->count();
        $list = db('course_class')->alias('cc')
                ->join('course c','c.courseid = cc.courseid')
                ->where($where)
                ->order('c.schoolovertime DESC')
                ->limit(($p-1)*$pageSize,$pageSize)
                ->select();
        if(!empty($list)){
            foreach($list as $k => $v){
                //课程状态
                if($v['schooltime'] > time()){
                    $list[$k]['status_str'] = 1;
                }else{
                    if($v['schoolovertime'] < time()){
                        $list[$k]['status_str'] = 3;
                    }else{
                        $list[$k]['status_str'] = 2;
                    }
                }

                $list[$k]['speaker'] = json_decode($v['speaker'], 1);
                //上课时间
                $list[$k]['schooltime'] = date('Y-m-d H:i:s',$v['schooltime']);
                if($v['status'] == 1){
                    //申请截至时间
                    $list[$k]['deadline'] = date('Y-m-d H:i:s',$v['deadline']);
                }
                //该课程参与班级
                $class = $this->GetClassesByCourseId($sid,$v['courseid']);
                if(!empty($class)){
                    $list[$k]['classes'] = implode(',',$class);
                }else{
                    $list[$k]['classes'] = '';
                }
                //课程试听会员人数
                $list[$k]['apply_num'] = $this->GetStudentNumByCourseId($sid,$v['courseid'],2);
                $list[$k]['apply_affirm_num'] = $this->GetAffirmNumByCourseId($sid,$v['courseid'],2);
                //课程正式学员人数
                $list[$k]['ourclass_num'] = $this->GetStudentNumByCourseId($sid,$v['courseid'],1);
                $list[$k]['ourclass_affirm_num'] = $this->GetAffirmNumByCourseId($sid,$v['courseid'],1);



            }
        }
        return ['content' => $list,'page' =>['count' =>$list_count]];

    }

    /**
     * 获取非本班级课程列表
     * @param $sid
     * @param $classid
     * @param string $search
     * @param int $p
     * @param int $pageSize
     * @return false|\PDOStatement|string|\think\Collection
     */
    public function GetNotOwnClassCourseList($sid,$classid,$search = '',$p = 1,$pageSize = 10){
        $where_course = [
            'classid' => $classid
        ];
        $ids = db('course_class')->where($where_course)->field('courseid')->select();
        //该店铺的，未开始课程
        $where = [
            'sid' => $sid,
            'schooltime' => ['>',time()]
        ];
        if(!empty($ids)){
            foreach($ids as $v){
                $ids_array[] = $v['courseid'];
            }
            $where['courseid'] = ['not in',$ids_array];
        }
        if(!empty($search)){
            $where['name|speaker'] =['like','%'.$search.'%'];
        }
        $list_count = db('course')->where($where)->count();
        $list = db('course')->where($where)->limit(($p-1)*$pageSize,$pageSize)->select();
        if(!empty($list)){
            foreach($list as $k => $v){
                $list[$k]['addtime'] = date('Y-m-d H:i:s',$v['addtime']);
                $list[$k]['begintime'] = date('Y-m-d H:i:s',$v['schooltime']);
                $list[$k]['timelength'] = ceil(($v['schoolovertime']-$v['schooltime'])/3600);
                if($v['status'] == 1){
                    $list[$k]['deadline'] = date('Y-m-d H:i:s',$v['deadline']);
                }
                $list[$k]['classes'] = $this->GetClassesByCourseId($sid,$v['courseid']);
                $list[$k]['student_num'] = $this->GetStudentNumByCourseId($sid,$v['courseid']);
            }
        }
        return ['content' => $list,'page' =>['count' =>$list_count]];

    }

    /**
     * 获取参加某个课程的所有班级
     * @param $sid
     * @param $courseid
     * @return array
     */
    public function GetClassesByCourseId($sid,$courseid){
        $where = [
            'cc.courseid' => $courseid,
            'c.sid' => $sid,
            'c.status' => ['neq',-1]
        ];
        $list = db('course_class')->alias('cc')
                ->join('classes c','c.classid = cc.classid')
                ->where($where)
                ->field('name')
                ->select();
        if(!empty($list)){
            foreach($list as $v){
                $res[] = $v['name'];
            }
        }else{
            $res = [];
        }
        return $res;
    }

    /**
     * 获取某个课程参与人数
     * @param $sid
     * @param $courseid
     * @param $type 0-所有人，1-正式学员，2-试听学员
     * @return int|string
     */
    public function GetStudentNumByCourseId($sid,$courseid,$type = 0){
        $where = [
            'sid' => $sid,
            'courseid' => $courseid
        ];
        if($type == 1){
            $where['ourclass_status'] = 1;
        }
        if($type == 2){
            $where['apply_status'] = 1;
            $where['ourclass_status'] = 0;
        }
        return db('course_students')->where($where)->count();
    }

    /**
     * 获取某个课程确认参与人数
     * @param $sid
     * @param $courseid
     * @param $type 0-所有人，1-正式学员，2-试听学员
     * @return int|string
     */
    public function GetAffirmNumByCourseId($sid,$courseid,$type = 0){
        $where = [
            'sid' => $sid,
            'courseid' => $courseid,
            'attend_status' => 1
        ];
        if($type == 1){
            $where['ourclass_status'] = 1;
        }
        if($type == 2){
            $where['apply_status'] = 1;
            $where['ourclass_status'] = 0;
        }
        return db('course_students')->where($where)->count();
    }

    /**
     * 解绑学员
     * @param $sid
     * @param $classid
     * @param $studentsid
     * @return array
     * @throws \think\Exception
     */
    public function UnbindStudent($sid, $classid, $studentsid){
        $where = [
            'sid' => $sid,
            'studentsid' => $studentsid,
            'classid' => $classid
        ];
        $res = db('class_students')->where($where)->delete();
        if($res === false){
            return ['status' => 0];
        }else{
            //classes表
            db('classes')->where(['classid' => $classid,'sid' => $sid, 'total_numbe' => ['>', 0]])->setDec('total_numbe');
            //course_class表中
            $cc_where = [
                'classid' => $classid
            ];
            $course_list = db('course_class')->where($cc_where)->field('courseid')->select();
            if(!empty($course_list)){
                foreach($course_list as $v){
                    $course_ids[] = $v['courseid'];
                }
                //course_students
                $cs_where = [
//                    'uid' => $uid,
                    'studentsid' => $studentsid,
                    'courseid' => ['in',$course_ids],
                    'sid' => $sid,
                    'sign_status' => 0
                ];
                db('course_students')->where($cs_where)->delete();
            }
            return ['status' => 1];
        }
    }

    /**
     * 解绑课程
     * @param $sid
     * @param $classid
     * @param $courseid
     * @return array
     * @throws \think\Exception
     */
    public function UnbindCourse($sid,$classid,$courseid){
        $where = [
            'classid' => $classid,
            'courseid' => $courseid
        ];
        $res = db('course_class')->where($where)->delete();
        if($res === false){
            return ['status' => 0];
        }else{
            //class_students
            $cs_where = [
                'classid' => $classid,
                'sid' => $sid
            ];
            $user_list = db('class_students')->where($cs_where)->field('uid')->select();
            if(!empty($user_list)){
                foreach($user_list as $v){
                    $uids[] = $v['uid'];
                }
                //course_students
                $cs_where = [
                    'uid' => ['in',$uids],
                    'courseid' => $courseid,
                    'sid' => $sid,
                    'sign_status' => 0
                ];
                db('course_students')->where($cs_where)->delete();
            }
            return ['status' => 1];
        }
    }


    /**
     * 微信端获取模版班级详情
     * @param $sid
     * @param $uid
     * @param $class_id 模版班级ID
     * @return array
     */
    public function getClassLibraryDetail($sid, $uid, $class_id){
        //判断是否为管理员
        $user = db('user_integral')->where(['userid' => $uid, 'sid' => $sid])->find();
        if($user['is_administrator'] != 1){
            return ['status' => 0, 'msg' => '非法请求'];
        }

        //是否为模版店铺班级
        $tpl_class = db('classes')
                    ->field('classid,name,description')
                    ->where(['sid' => config('template_sid'), 'classid' => $class_id, 'status' => ['<>', -1]])
                    ->find();
        if(!$tpl_class){
            return ['status' => 0, 'msg' => '班级不存在'];
        }

        //查询自身店铺是否引用此班级
        $self_class = db('classes')->where(['sid' => $sid, 'origin_classid' => $class_id, 'status' => ['<>', -1]])->find();
        $tpl_class['is_quote'] = $self_class ? 1 : 0;
        return ['status' => 1, 'msg' => '获取成功', 'data' => $tpl_class];
    }


    /**
     * 通过用户ID获取自身班级列表
     * @param $sid
     * @param $uid
     * @return mixed
     */
    public function getOwnClassListByUid($sid, $uid){
        $field = 'c.classid,c.name,c.status,c.teaching_status';
        $where = [
            'cs.uid' => $uid,
            'cs.sid' => $sid,
            'c.status' => ['<>', -1]
        ];
        $list = db('class_students cs')
                ->field($field)
                ->join('classes c', 'cs.classid=c.classid')
                ->where($where)
                ->order('c.status DESC,c.teaching_status DESC,c.addtime DESC')
                ->select();

        if($list){
            foreach($list as $k => $v){
                //cur_status 0:已结课；1:进行中；2:预告
                $list[$k]['cur_status'] = $v['status'] == 0 ? 0 : ($v['teaching_status'] == 1 ? 1 : 2);
                unset($list[$k]['status']);
                unset($list[$k]['teaching_status']);
            }
        }

        return $list;
    }


    /**
     * 通过用户ID获取其他班级列表
     * @param $sid
     * @param $uid
     * @param $p
     * @param $pageSize
     * @return mixed
     */
    public function getOtherClassListByUid($sid, $uid, $p, $pageSize){
        $own_classes = db('class_students')->field('classid')->where(['sid' => $sid, 'uid' => $uid])->select();
        $where = [
            'sid' => $sid,
            'status' => ['<>', -1]
        ];
        if($own_classes){
            foreach($own_classes as $k => $v){
                $own_class_ids[$k] = $v['classid'];
            }
            $where['classid'] = ['not in', $own_class_ids];
        }
        $field = 'classid,name,status,teaching_status';
        $list = db('classes')
                ->field($field)
                ->where($where)
                ->limit(($p - 1)*$pageSize, $pageSize)
                ->order('status DESC,teaching_status ASC,addtime DESC')
                ->select();
        if($list){
            foreach($list as $k => $v){
                //cur_status 0:已结课；1:进行中；2:预告
                $list[$k]['cur_status'] = $v['status'] == 0 ? 0 : ($v['teaching_status'] == 1 ? 1 : 2);
                unset($list[$k]['status']);
                unset($list[$k]['teaching_status']);
            }
        }
        return $list;
    }


    /**
     * 微信端: 获取未开始的班级课程列表
     * @param $sid
     * @param $uid
     * @param $class_id
     * @return mixed
     */
    public function getUnstartClassCourseList($sid, $class_id){
        $where = [
            'cc.classid' => $class_id,
            'c.sid' => $sid,
            'c.schooltime' => ['>', time()],
            'c.course_status' => 1
        ];
        $list = db('course_class cc')
                ->field('c.courseid,c.name,c.speaker,c.schooltime,c.pic')
                ->join('course c', 'c.courseid = cc.courseid')
                ->where($where)
                ->order('c.schooltime DESC')
                ->select();

        if($list){
            foreach($list as $k => $v){
                $list[$k]['schooltime'] = date('Y/m/d H:i', $v['schooltime']);
                $list[$k]['speaker'] = json_decode($v['speaker'], 1);
            }
        }
        return $list;
    }


    /**
     * 微信端: 获取班级活动
     * @param $sid
     * @param $class_id
     * @return array
     */
    public function getClassActivity($sid, $uid, $class_id){
        $magazine_cate_id = db('classes')
                            ->where(['sid' => $sid, 'classid' => $class_id, 'status' => 1])
                            ->value('magazine_cate_id');
        $storeService = new StoreService();
        return $storeService->getLatestActivityByCateId($sid, $uid, $magazine_cate_id);
    }


    /**
     * 微信端: 获取班级基本信息和用户状态
     * @param $sid
     * @param $uid
     * @param $classid
     * @return bool]
     */
    public function getClassDetailAndUserStatus($sid, $uid, $classid){
        $info = db('classes')->field('name,description,banner,magazine_cate_id')->where(['sid' => $sid, 'classid' => $classid, 'status' => ['<>', -1]])->find();
        if(!$info){
            return false;
        }
        $info['magazine_cate_link'] = $info['magazine_cate_id'] ? $this->domain.'/m/html/magazine_list.html?sid='.$sid.'&uid='.$uid.'&cid='.$info['magazine_cate_id'] : '';

        if($info['banner']){
            $info['banner'] = json_decode($info['banner'], 1);
        }
//        $formal_status = db('students')->where(['sid' => $sid, 'uid' => $uid])->value('formal_status');
        $class_students = db('class_students')->where(['sid' => $sid, 'classid' => $classid, 'uid' => $uid])->find();
        $class_students_status = $class_students ? 1 : 0;
        if(!$class_students_status){
            //判断是否为学员顾问访问
            $counselor = db('user_integral')->where(['parent_id|counselor_id' => $uid])->find();
            $class_students_status = $counselor ? 1 : 0;
        }
        $info['class_students_status'] = $class_students_status;

        $info['formal_status'] = db('students')->where(['sid' => $sid, 'uid' => $uid])->value('formal_status');

        return $info;
    }

    public function getClassListFront($sid){
        $list = db('classes')
                ->field('classid,name')
                ->where(['sid' => $sid, 'status' => 1])
                ->order('addtime DESC')
                ->select();
        return $list;
    }
}